#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>

int main(int argc ,char *argv[])
{

	pid_t id = fork();

	if(id<0)
	{
		perror("fork");
		exit(EXIT_FAILURE);
	}
	else if(id == 0)
	{
		//子进程
		if (argc < 2) 
		{ 
			// 简单判断是否有足够参数传递给新程序
            		printf("请传入要执行程序的参数\n");
            		exit(EXIT_FAILURE);
        	}

		char *myargv[argc];
		int i=0;
		
		while(argv[1+i])
		{
			myargv[i] = argv[i+1];
			i++;
		}
		myargv[i] = NULL;
		execv(myargv[0] ,myargv);
		
		perror("execv failed");
		exit(EXIT_FAILURE);
	}
	else
	{
		//父进程
		printf("这是父进程：pid = %d, 等待子进程：pid = %d\n",getpid(),id);
		int status;
		waitpid(id ,&status ,0);

		printf("子进程已完成，父进程等待成功退出!\n");
	}	
		
		
	//pid_t id = fork();
	//if(id<0)
	//{
	//	perror("fork");
	//	exit(EXIT_FAILURE);
	//}
	//else if(id == 0)
	//{
	//	//子进程
	//	char *program = "/usr/bin/ls";
	//	char *myargv[] = {"-a","-l",NULL};

	//	execv(program ,myargv);
	//	perror("execv failed");
	//	exit(EXIT_FAILURE);
	//}
	//else
	//{
	//	//父进程
	//	printf("这是父进程：ppid = %d, 等待子进程：pid = %d\n",getpid(),id);
	//	int status;
	//	waitpid(id ,&status ,0);

	//	printf("子进程已完成，父进程等待成功退出!\n");
	//	exit(EXIT_SUCCESS);
	//}
	
	
	
	
	//pid_t id = fork();

	//if(id<0)
	//{
	//	fprintf(stderr ,"Fork Failed\n");
	//	exit(EXIT_FAILURE);
	//}
	//else if(id == 0)
	//{
	//	//子进程
	//	char **myargv = &argv[1];
	//	execv(myargv[0],myargv);
	//}
	//else
	//{
	//	//父进程
	//		pid_t rid = waitpid(id,NULL,0);	
	//		sleep(1);
	//		if(rid>0)
	//			break;
	//}


	return 0;
}
